<?php
class arcService extends commonService{
    
    public function __construct(){
        parent::__construct();
		$this->mid=11;
		
		$this->table_admin=table('admin');
		$this->fields=array();
        $this->url_service=load_service('url',P_SVC);
        $this->url_service->set_module_id(11);
        $this->pagesize=$this->url_service->pagesize();
        
        $this->include_viewer_dir=P_VIEWER.'archtml/';
		$this->def_temp='show.php';
    }
    public function t(){
        return array('arc','arc_data','category','attrtaglist');
    }
    public function my_template($selected=''){
        $dir=$this->include_viewer_dir;
        $t=template_files($dir);
        unset($t[$this->def_temp]);
        $default="<option value=''>默认模板[{$this->def_temp}]</option>\r\n";
        return $default.form_select($t,$selected);
    }
    public function flag_data(){
        return array(
            0=>'-',
            1=>'头条',
            2=>'推荐',
            3=>'幻灯',
            4=>'特荐',
            5=>'滚动',
            6=>'加粗',
            7=>'图片',
            8=>'跳转',
        );
    }
	//批量删除
	public function delete($items){
		$str=implode(',',$items);
		$this->m->query("delete from `{$this->t[0]}` where `id` in ($str)");
		return true;
	}
	//文章重复检测 添加 编辑时用
	public function ajax_title_check($title,$id=''){
		$sql='';
		$d=array();
		$d['title']=$title;
		if($id){ 
			$sql.=" and `id`!=:id";
			$d['id']=$id;
		}
		$query="select `id` from `{$this->t[0]}` where `title`=:title {$sql} limit 1";
		return intval($this->m->get_field($query,$d));
	}
	////////////////////////////////////////////////////////////////////////////////
	
	//更新ismake
	public function update_ismake($id){
		$query="update `{$this->t[0]}` set `ismake`='1' where `id`=:id limit 1";
		return $this->m->query($query,array('id'=>$id));
	}
	//批量更新arc address
	public function update_address($items){
		if(!is_array($items)) return false;
		if(!count($items)) return false;
		$svc=load_service('archtml',P_SVC);
		foreach($items as $k=>$v){
			$svc->_update($v);
		}
		return true;
	}
	//批量更新arc html
	public function make_html($items){
		if(!is_array($items)) return false;
		if(!count($items)) return false;
		$svc=load_service('archtml',P_SVC);
		foreach($items as $k=>$v){
			$svc->_show($v);
			$this->update_ismake($v);//更新字段
		}
		return true;
	}
	//批量更新arc flag
	public function update_flag($items,$d){
		$str=implode(',',$items);
		return $this->m->query("update `{$this->t[0]}` set `flag`=:d where `id` in ($str)",array('d'=>$d));
	}
	//批量更新arc status
	public function update_status($items,$d){
		$str=implode(',',$items);
		$this->m->query("update `{$this->t[0]}` set `status`=:d where `id` in ($str)",array('d'=>$d));
		//htmlurl ismake 删除html
		if($d==1){
			$this->update_address($items);
			$this->make_html($items);
		}else{
			$this->empty_htmlurl($items);
			$this->unlink_html($items);
		}
		return true;
	}
	//从arc_data中取content
	public function get_content($id){
		$query="select `content` from `{$this->t[1]}` where `id`=:id limit 1";
		return $this->m->get_field($query,array('id'=>$id));
	}
	//取得描述
	private function get_desc($content,$length=120){
		if($length){
			$str=trim(strip_tags($content));
			$str=preg_replace("/&([a-z]{1,});/",'',$str);
			//return addslashes(stripslashes(dsubstr($str,$length)));
			return stripslashes(dsubstr($str,$length));
		}else{
			return '';
		}
	}
    public function add_($post){
        $result=array();
        $post['edit_man']='';
        $post['edit_time']=time();
        $post['hits']='0';
        $post['arcurl']='';
        $post['htmlurl']='';
        $post['ismake']='0';
		$post['goodpost']=0;
		$post['badpost']=0;
		
		if($post['content'] && !$post['description']){
			$post['description']=$this->get_desc($post['content'],120);
		}
		
        $vali=validate::check('arc',$post,'add');
        if($vali){
            $result[0]=$this->model->_i($this->t[0],$post);
			//插入到arc_data表中
			if($result[0]){
				$insert_id=$this->m->insert_id();
				if($post['status']==1){
					//更新htmlurl 以status=1为准
					$this->update_address(array($insert_id));
					//生成静态
					//$this->make_html(array($insert_id));
				}else{
					
				}
				$_data=array('id'=>$insert_id,'content'=>$post['content']);
				$this->model->_i($this->t[1],$_data);
				$result[2]=$insert_id;//返回给attrtaglist用
			}	
        }else{
            $result[0]=false;
            $result[1]="\\n".implode("\\n",validate::getMsg());
        }
        return $result;
    }
    public function mod($id){
        $data=$this->model->_f($this->t[0],'*',$id);
        $data2=$this->model->_f($this->t[1],'*',$id);
		$data['content']=$data2['content'];//获取content
		return $data;
    }
	//编辑时用
	private function empty_htmlurl($items){
		if(!is_array($items)) return false;
		if(!count($items)) return false;
		foreach($items as $k=>$v){
			$query="update `{$this->t[0]}` set `htmlurl`='',`ismake`='0' where `id`=:id limit 1";
			$this->m->query($query,array('id'=>$v));
		}
		return true;
	}
	//生成htmlurl 
	//内部unlink_html使用
	private function _htmlurl($timestring,$id){
		//'static_rule_show'=>array('/html/{cat}/{id}.html',ROOT.'html/{cat}/{id}.html'),
		//$rule=$this->conf->static_rule_show;
		//$http=$rule[0];
        //$file=$rule[1];
		
		$c=date('Ym',$timestring);
		//$http=str_replace(array('{cat}','{id}'),array($c,$id),$http);
		//$file=str_replace(array('{cat}','{id}'),array($c,$id),$file);
        list($http,$file)=$this->url_service->var_show($c,$id)->show();
		
		return $http;
	}
	//编辑 删除时用
	private function unlink_html($items){
		if(!is_array($items)) return false;
		if(!count($items)) return false;
		foreach($items as $k=>$v){
			$query="select `id`,`add_time` from `{$this->t[0]}` where `id`=:id limit 1";
			$r=$this->m->select($query,array('id'=>$v));
			if(!$r['id']) continue;
			$http=$this->_htmlurl($r['add_time'],$v);
			$file=ROOT.trim($http,'/');
			if($http && file_exists($file)) unlink($file);
		}
		return true;
	}
    public function mod_($post,$id){
        $result=array();
        $post['edit_time']=time();
		
		if($post['content'] && !$post['description']){
			$post['description']=$this->get_desc($post['content'],120);
		}
        
        $vali=validate::check('arc',$post,'mod',array('id::!='=>$id));
        if($vali){
    		$result[0]=$this->model->_u($this->t[0],$post,$id);
			//更新到arc_data表中
			if($result[0]){
				if($post['status']==1){
					//更新htmlurl 以status=1为准
					$this->update_address(array($id));
					//生成静态
					$this->make_html(array($id));
				}else{
					//更新htmlurl
					$this->empty_htmlurl(array($id));
					//删除html
					$this->unlink_html(array($id));
				}
				$_data=array('content'=>$post['content']);
				$this->model->_u($this->t[1],$_data,$id);
			}
    	}else{
    		$result[0]=false;
            $result[1]="\\n".implode("\\n",validate::getMsg());
    	}
        return $result;
    }
    public function del($id){
        $return=array();
		//查询htmlurl
		$query="select `id` from `{$this->t[0]}` where `id`=:id limit 1";
		$r=$this->m->select($query,array('id'=>$id));
		if(!$r['id']){
			$return[0]=false;
			return $return;
		}
		
		$this->unlink_html(array($id));//删html
		
        $return[0]=$this->model->_d($this->t[0],$id);//删除arc
		$this->model->_d($this->t[1],$id);//删除arc_data
		$this->m->query("delete from `{$this->t[3]}` where `arc_id`=:arc_id",array('arc_id'=>$id));//删除attrtaglist
		
        return $return;
    }
    public function li($condition=array(),$extra='',$extra_data=array()){
        $return=array();
        $query="select * from `{$this->t[0]}` where 1 {$extra} order by `id` desc";
        $p=new smart_pager(array($query,$extra_data),$this->m);
        //$p->address('&block_id=%block_id%','block_id',$condition['block_id']);
		foreach($condition as $k=>$v){
			$p->address("&{$k}=%{$k}%",$k,$v);
		}
        if($p->total_num>0){
            $return[]=$this->m->mselect($p->query,$extra_data);
            $return[]=$p;
        }
        return $return;
    }
	/////////////////////////////////////////////////////////////////////////////////////////////
	public function return_min_max(){
		$query="select min(`id`),max(`id`) from `{$this->t[0]}` where `status`='1'";
		return $this->m->select($query,array(),'NUM');
	}
	public function all(){
		//unset($_SESSION['task_my']);
		if(!isset($_SESSION['task_my'])){
			//update index list show
			$_SESSION['task_my']=array();
			$_SESSION['task_my'][0]=0;
			$_SESSION['task_my'][1]=array(
				array('html_update',url('arc','html_','k=update')),
				array('html_index',url('arc','html_','k=index')),
				array('html_list',url('arc','html_','k=list')),
				array('html_show',url('arc','html_','k=show'))
			);
		}
		if(intval($_SESSION['task_my'][0])>=1){
			alert('一键生成只能同时进行一次！');
			back();
		}else{
			$_SESSION['task_my'][0]++;
		}
		$task=$this->all_start();
		//if($task) $this->$task[0]();
		if($task){
			exit(js("location.href='{$task[1]}'"));
		}
	}
	private function all_start(){
		if(!isset($_SESSION['task_my'])) return false;
		$task=array_shift($_SESSION['task_my'][1]);
		if($task==false){
			unset($_SESSION['task_my']);
			return false;
		}
		return $task;
	}
	//生成静态部分 静态生成链接调用
	//ok
	public function html_index($data=array()){
		$m='arc';
		$a='html';
		$k='index';
		$svc=load_service('archtml',P_SVC);
		$svc->_index();////
		$msg='首页生成成功';
		
		$task=$this->all_start();
		if($task){
			$url=$task[1];
		}else{
			$url=url($m,$a);
		}
		include(VIEWER_DIR.'shell/tip.php');
		exit;
	}
	//ok
	public function html_list($data=array()){
		$m='arc';
		$a='html';
		$aa='html_';
		$k='list';
		$svc=load_service('archtml',P_SVC);
		
		if($_POST){
			$catids=$_POST['catids'];
			$fid   =$_POST['fid'];
			$tid   =$_POST['tid'];
			$fpage =$_POST['fpage'];
			$page_id=$_POST['page_id'];
		}else{
			$catids=$_GET['catids'];
			$fid   =$_GET['fid'];
			$tid   =$_GET['tid'];
			$fpage =$_GET['fpage'];
			$page_id=$_GET['page_id'];
		}
		
		if(isset($catids)){
			$query="select * from `{$this->t[2]}` where `mid`='{$this->mid}' and `id`>:id order by `id` asc";
			$CAT=$this->m->select($query,array('id'=>$catids));
			if($CAT){
				$bcatid=$catid=$CAT['id'];
				$_c=$this->m->get_field("select count(*) from `{$this->t[0]}` where `status`='1' and `arccat_id`=:arccat_id",array('arccat_id'=>$catid));
				$total=max(ceil(intval($_c)/$this->pagesize),1);
				$num=50;
				$bfid=$fid;
				isset($fpage) or $fpage = 1;
				if($fpage<=$total){
					$fid=$fpage;
					$svc->_list($catid,$page_id,$this->pagesize,$fid,$num);////
					$fid=$bfid;
					$msg='['.$CAT['name'].'] 第'.$fpage.'页至第'.($fpage+$num-1).'页生成成功'.$this->progress(0, $fid, $tid);
					$url=url($m,$aa,'k='.$k.'&catids='.$catids.'&fid='.$fid.'&tid='.$tid.'&fpage='.($fpage+$num));
					include(VIEWER_DIR.'shell/tip.php');
					exit;
				}
				$fid++;
				$msg='['.$CAT['name'].'] 生成成功'.$this->progress(0, $fid, $tid);
				$url=url($m,$aa,'k='.$k.'&catids='.$catid.'&fid='.$fid.'&tid='.$tid);
				include(VIEWER_DIR.'shell/tip.php');
				exit;
			}else{
				$task=$this->all_start();
				if($task){
					exit(js("location.href='{$task[1]}'"));
				}else{
					jump($m,$a);//生成完毕跳转
				}
			}		
		}else{
			$query="select count(*) from `{$this->t[2]}` where `mid`='{$this->mid}'";
			$tid = $this->m->get_field($query);
			jump($m,$aa,'k='.$k.'&catids=0&fid=1&&tid='.$tid);
		}
		
	}
	//ok
	public function html_show($data=array()){
		$m='arc';
		$a='html';
		$aa='html_';
		$k='show';
		$svc=load_service('archtml',P_SVC);
		
		if($_POST){
			$catid=$_POST['catid'];
			$fid  =$_POST['fid'];
			$sid  =$_POST['sid'];
			$tid  =$_POST['tid'];
			$num  =$_POST['num'];
		}else{
			$catid=$_GET['catid'];
			$fid  =$_GET['fid'];
			$sid  =$_GET['sid'];
			$tid  =$_GET['tid'];
			$num  =$_GET['num'];
		}
		
		$catid = isset($catid) ? intval($catid) : '';
		$sql = $catid ? " and `arccat_id`=:catid" : '';
		$d = $catid ? array('catid'=>$catid) : array() ;
		
		if(!isset($fid)){
			$query="select min(`id`) from `{$this->t[0]}` where `status`='1' {$sql}";
			$fid=intval($this->m->get_field($query,$d));
		}
		isset($sid) or $sid=$fid;
		if(!isset($tid)){
			$query="select max(`id`) from {$this->t[0]} where `status`='1' {$sql}";
			$tid=intval($this->m->get_field($query,$d));
		}
		isset($num) or $num=100;
		if($fid<=$tid){
			$query="select `id` from {$this->t[0]} where `status`='1' and `id`>=:id {$sql} order by `id` asc limit 0,$num";
			$info=$this->m->mselect($query,array_merge($d,array('id'=>$fid)));
			if(isset($info[0]['id']) and is_array($info)){
				foreach($info as $_key=>$_value){
					$itemid=$_value['id'];
					$svc->_show($itemid);////
					$this->update_ismake($itemid);
				}
				$itemid+=1;
			}else{
				$itemid=$fid+$num;
			}
		}else{
			$task=$this->all_start();
			if($task){
				exit(js("location.href='{$task[1]}'"));
			}else{
				jump($m,$a);//生成完毕跳转
			}
		}
		$msg='ID从'.$fid.'至'.($itemid-1).'生成成功'.$this->progress($sid, $fid, $tid);
		$url=url($m,$aa,"k=$k&sid=$sid&fid=$itemid&tid=$tid&num=$num");
		include(VIEWER_DIR.'shell/tip.php');
		exit;
	}
	//ok
	public function html_update($data=array()){
		$m='arc';
		$a='html';
		$aa='html_';
		$k='update';
		$svc=load_service('archtml',P_SVC);
		
		if($_POST){
			$catid=$_POST['catid'];
			$fid  =$_POST['fid'];
			$sid  =$_POST['sid'];
			$tid  =$_POST['tid'];
			$num  =$_POST['num'];
		}else{
			$catid=$_GET['catid'];
			$fid  =$_GET['fid'];
			$sid  =$_GET['sid'];
			$tid  =$_GET['tid'];
			$num  =$_GET['num'];
		}
		
		$catid = isset($catid) ? intval($catid) : '';
		$sql = $catid ? " and `arccat_id`=:catid" : '';
		$d= $catid ? array('catid'=>$catid) : array() ;
		
		if(!isset($fid)){
			$query="select min(`id`) from `{$this->t[0]}` where `status`='1' {$sql}";
			$fid=intval($this->m->get_field($query,$d));
		}
		isset($sid) or $sid=$fid;
		if(!isset($tid)){
			$query="select max(`id`) from {$this->t[0]} where `status`='1' {$sql}";
			$tid=intval($this->m->get_field($query,$d));
		}
		isset($num) or $num=100;
		if($fid<=$tid){
			$query="select `id` from {$this->t[0]} where `status`='1' and `id`>=:id {$sql} order by `id` asc limit 0,$num";
			$info=$this->m->mselect($query,array_merge($d,array('id'=>$fid)));
			if(isset($info[0]['id']) and is_array($info)){
				foreach($info as $_key=>$_value){
					$itemid=$_value['id'];
					$svc->_update($itemid);////
				}
				$itemid+=1;
			}else{
				$itemid=$fid+$num;
			}
		}else{
			$task=$this->all_start();
			if($task){
				exit(js("location.href='{$task[1]}'"));
			}else{
				jump($m,$a);//生成完毕跳转
			}
		}
		$msg='ID从'.$fid.'至'.($itemid-1).'地址更新成功'.$this->progress($sid, $fid, $tid);
		$url=url($m,$aa,"k=$k&sid=$sid&fid=$itemid&tid=$tid&num=$num");
		include(VIEWER_DIR.'shell/tip.php');
		exit;
	}
	//ok
	public function html_cate($data=array()){
		$m='arc';
		$a='html';
		$aa='html_';
		$k='cate';
		$svc=load_service('archtml',P_SVC);
		
		if($_POST){
			$catid=$_POST['catid'];
			$num  =$_POST['num'];
			$fid  =$_POST['fid'];
			$fpage=$_POST['fpage'];
			$tpage=$_POST['tpage'];
			$page_id=$_POST['page_id'];
		}else{
			$catid=$_GET['catid'];
			$num  =$_GET['num'];
			$fid  =$_GET['fid'];
			$fpage=$_GET['fpage'];
			$tpage=$_GET['tpage'];
			$page_id=$_GET['page_id'];
		}
		if(!$catid){
			alert('请选择分类！');
			back();
		}
		isset($num) or $num = 50;
		isset($fid) or $fid = 1;
		$_c=$this->m->get_field("select count(*) from `{$this->t[0]}` where `status`='1' and `arccat_id`=:catid",array('catid'=>$catid));
		$total=max(ceil(intval($_c)/$this->pagesize),1);
		if($fpage && $tpage){
			$fid=$fpage;
			$num=$tpage-$fpage+1;
			$svc->_list($catid,$page_id,$this->pagesize,$fid,$num);////
			jump($m,$a);
		}
		if($fid<=$total){
			$svc->_list($catid,$page_id,$this->pagesize,$fid,$num);////
			$msg='第'.$fid.'页至第'.($fid+$num-1).'页生成成功';
			$url=url($m,$aa,'k='.$k.'&catid='.$catid.'&fid='.($fid+$num).'&num='.$num.'&fpage='.$fpage.'&tpage='.$tpage);
			include(VIEWER_DIR.'shell/tip.php');
			exit;
		}else{
			jump($m,$a);
		}
	}
	//ok
	public function html_item($data=array()){
		$m='arc';
		$a='html';
		$aa='html_';
		$k='show';
		if($_POST){
			$catid=$_POST['catid'];
			$num  =$_POST['num'];
		}else{
			$catid=$_GET['catid'];
			$num  =$_GET['num'];
		}
		if(!$catid){
			alert('请选择分类！');
			back();
		}
		jump($m,$aa,'k='.$k.'&catid='.$catid.'&num='.$num);

	}
	//生成静态部分
	
	private function progress($sid, $fid, $tid) {
		if($tid > $sid && $fid < $tid) {
			$p = round(($fid-$sid)*100/($tid-$sid));
			if($p > 100) $p = 100;
			$p = $p.'%';
		} else {
			$p = '100%';
		}
		return '<table cellpadding="0" cellspacing="0" width="100%" style="margin:0"><tr><td><div class="progress"><div style="width:'.$p.';">&nbsp;</div></div></td><td style="color:#666666;font-size:10px;width:40px;text-align:center;">'.$p.'</td></tr></table>';
	}
	
	//数据字段列表
	public function get_fields(){
		if(empty($this->fields)){
			$fields=array();
			$query="desc `{$this->t[0]}`";
			$info=$this->m->mselect($query);
			foreach($info as $k=>$v){
				$fields[]=strtolower($v['Field']);
			}
			$this->fields=$fields;
		}
		return $this->fields;
	}
	//数据导出
	public function dump_export($in,$with_title=1,$type='range'){
		$return=array(0=>true,1=>'导出成功！');
		
		$data=array();
		switch($type){
			case 'range':
			
			if(!isset($in['start']) or !isset($in['stop'])){
				$return[0]=false;
				$return[1]='type error！';
				return $return;
			}
			$start=$in['start'];
			$stop=$in['stop'];
			$start=abs(intval($start));
			$stop=abs(intval($stop));
			if($start>$stop){
				$return[0]=false;
				$return[1]='开始ID不能大于结束ID！';
				return $return;
			}
			if($start==0){
				$return[0]=false;
				$return[1]='开始ID为0！';
				return $return;
			}
			if($stop==0){
				$return[0]=false;
				$return[1]='结束ID为0！';
				return $return;
			}
			
			$query="select * from `{$this->t[0]}` where `id`>=:start and `id`<=:stop order by `id` asc";
			$data=$this->m->mselect($query,array('start'=>$start,'stop'=>$stop));
			break;
			////
			case 'single':
				$ids=implode(',',$in);
				$query="select * from `{$this->t[0]}` where `id` in ($ids) order by `id` asc";
				$data=$this->m->mselect($query);
			break;
			default:
				return array(false,'');
			break;
		}
		
		if(empty($data)){
			$return[0]=false;
			$return[1]='数据库中没有数据！';
			return $return;
		}
		$file=PROJECT_PATH.'runtime/data_out.xls';
		$excel=new ExcelWriter($file);
		if(!$excel){
			$return[0]=false;
			$return[1]=$excel->error;
			return $return;
		}
		if($with_title) array_unshift($data,$this->get_fields());
		
		foreach($data as $v) $excel->writeLine($v);
		$excel->sendfile($file);
		
		return $return;
	}
	//数据导入
	public function dump_import($c){
		$success=0;
		$return=array(0=>true,1=>'导入成功！');
		
		$data=array();
		
		$c['start_row']=abs(intval($c['start_row']));
		
		if($c['start_row']==0){
			$return[0]=false;
			$return[1]='数据起始行错误！';
			return $return;
		}
		if(!$c['url']){
			$return[0]=false;
			$return[1]='文件路径不能为空！';
			return $return;
		}
		$file=ROOT.ltrim($c['url'],'/');
		if(!file_exists($file)){
			$return[0]=false;
			$return[1]='文件不存在！';
			return $return;
		}
		if(strtolower(pathinfo($file,PATHINFO_EXTENSION))!='xls'){
			$return[0]=false;
			$return[1]='文件类型不正确！';
			return $return;
		}
		$excel=new Spreadsheet_Excel_Reader();
		$excel->setOutputEncoding('UTF-8');
		$excel->read($file);
		
		if($excel->sheets[0]['numRows']==0){
			$return[0]=false;
			$return[1]='excel中没有数据！';
			return $return;
		}
		//从1开始
		for($i=$c['start_row'];$i<=$excel->sheets[0]['numRows'];$i++){
			$d=$excel->sheets[0]['cells'][$i];
			
			foreach($this->get_fields() as $k=>$v){
				if($v=='id'){
					if($c['with_id']) $data['id']=$d[1];
				}else{
					$data[$v]=$d[$k+1];
				}
			}
			
			//if($c['with_id']) $data['id']=$d[1];
			
			//$data['arccat_id']=$d[2];
			
			$r=$this->model->insert_by_array($this->t[0],$data);
			if($r) $success++;
		}
		
		$return=array(0=>true,1=>'导入成功！成功记录总数'.$success);
		
		return $return;
	}
//
}